package com.museum.guide.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.museum.guide.dto.GuideAppointmentDTO;
import com.museum.guide.entity.GuideAppointment;
import com.museum.guide.entity.Guide;
import com.museum.guide.entity.AppointmentTimeSlot;
import com.museum.guide.mapper.GuideAppointmentMapper;
import com.museum.guide.mapper.GuideMapper;
import com.museum.guide.mapper.AppointmentTimeSlotMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

/**
 * 讲解预约服务类
 */
@Service
public class GuideAppointmentService extends ServiceImpl<GuideAppointmentMapper, GuideAppointment> {


    @Autowired
    private AppointmentTimeSlotMapper timeSlotMapper;

    /**
     * 分页查询讲解预约列表
     *
     * @param page     页码
     * @param pageSize 每页条数
     * @param userId   用户ID
     * @param status   状态
     * @return 分页结果
     */
    public IPage<GuideAppointment> getPage(
            int page,
            int pageSize,
            Long userId,
            String status,
            Long guideId
    ) {
        // 构造分页对象
        Page<GuideAppointment> pageInfo = new Page<>(page, pageSize);

        // 构造条件
        LambdaQueryWrapper<GuideAppointment> queryWrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        if (userId != null) {
            queryWrapper.eq(GuideAppointment::getUserId, userId);
        }

        if (guideId != null) {
            queryWrapper.eq(GuideAppointment::getGuideId, guideId);
        }
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(GuideAppointment::getStatus, status);
        }

        // 添加排序条件
        queryWrapper.orderByDesc(GuideAppointment::getCreateTime);

        // 执行查询
        this.page(pageInfo, queryWrapper);

        return pageInfo;
    }

    /**
     * 新增讲解预约
     *
     * @param appointmentDTO 预约DTO
     * @return 结果
     */
    @Transactional
    public String save(GuideAppointmentDTO appointmentDTO) {
        // 验证时间段是否存在
        if (null == appointmentDTO.getId()) {
            AppointmentTimeSlot timeSlot = timeSlotMapper.selectById(appointmentDTO.getTimeSlotId());
            if (timeSlot == null) {
                throw new IllegalArgumentException("预约时间段不存在");
            }
        }

        // 创建预约实体
        GuideAppointment appointment = new GuideAppointment();
        BeanUtils.copyProperties(appointmentDTO, appointment);

        if (null == appointmentDTO.getId()) {
            // 设置用户ID和默认状态
            appointment.setStatus("PENDING");
        }

        this.saveOrUpdate(appointment);
        if (null == appointmentDTO.getId()) {
            return "预约申请提交成功，请等待审核";
        } else {
            return "修改预约信息成功";
        }
    }

    /**
     * 修改讲解预约状态
     *
     * @param id     预约ID
     * @param status 状态
     * @return 结果
     */
    @Transactional
    public String updateStatus(Long id, String status) {
        GuideAppointment appointment = super.getById(id);
        if (appointment == null) {
            throw new IllegalArgumentException("讲解预约不存在");
        }

        appointment.setStatus(status);
        this.updateById(appointment);

        String message;
        switch (status) {
            case "APPROVED":
                message = "预约已通过";
                break;
            case "REJECTED":
                message = "预约已拒绝";
                break;
            case "CANCELED":
                message = "预约已取消";
                break;
            default:
                message = "状态已更新";
        }

        return message;
    }

    /**
     * 取消讲解预约
     *
     * @param id     预约ID
     * @param userId 用户ID
     * @return 结果
     */
    @Transactional
    public String cancel(Long id, Long userId) {
        GuideAppointment appointment = super.getById(id);
        if (appointment == null) {
            throw new IllegalArgumentException("讲解预约不存在");
        }

        // 验证是否是自己的预约
        if (!appointment.getUserId().equals(userId)) {
            throw new IllegalArgumentException("只能取消自己的预约");
        }

        // 只有待审核和已通过的预约可以取消
        if (!"PENDING".equals(appointment.getStatus()) && !"APPROVED".equals(appointment.getStatus())) {
            throw new IllegalArgumentException("当前状态无法取消预约");
        }

        appointment.setStatus("CANCELED");
        this.updateById(appointment);

        return "预约已取消";
    }

    /**
     * 查询用户的讲解预约列表
     *
     * @param userId 用户ID
     * @return 预约列表
     */
    public List<GuideAppointment> listByUserId(Long userId) {
        LambdaQueryWrapper<GuideAppointment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GuideAppointment::getUserId, userId);
        queryWrapper.orderByDesc(GuideAppointment::getCreateTime);

        return this.list(queryWrapper);
    }
}